import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import storage from '../../shared/storage';
import {HomeService} from "../home.service";
import { Router, ActivatedRoute, NavigationEnd , ParamMap } from '@angular/router';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import SysData from '../../shared/sysData';
import { TranslateService } from '@ngx-translate/core';
import Mysocket from '../../shared/mySocket';
declare var $: any;
@Component({
  selector: 'app-device-debug-db112',
  templateUrl: './device-debug-db112.component.html',
  styleUrls: ['./device-debug-db112.component.scss']
})
export class DeviceDebugDb112Component implements OnInit {
  @Output() close: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output() offLine: EventEmitter<boolean> = new EventEmitter<boolean>();
  movefrequently=storage.getSessionStorage('movefrequently');//频率：50 || 60
  xtotal=0;
  isSpinning:boolean=false;
  waveDataXList=[];//波形图X轴
  waveDataYList=[]; //波形图Y轴
  formatOne = percent =>"";
  state=false;  //默认停止
  isAMmainShow:boolean=false;//主天线是否亮灯
  isAMsubsidiaryShow:boolean=false;//副天线是否亮灯
  isModeChangeShow:boolean=false;
  currentKeyVal={}; //现在的天线，key，value集合
  readParamItem={};//读取参数
  restoreFactoryItem={};//恢复出厂设置
  signalWaveOption={};//信号波形内容;折线图
  sameMoveList=[];//同步相移
  currentAnten;//当前天线
  //moduleCode
  db112Command:any=storage.getSessionStorage("AA10_DB112_CMD");   //db112通用调试命令
  db112PhaseShiftList:any=storage.getSessionStorage("AA10_DB112_PHASE_SHIFT");   //灵敏度
  db112VolumeList:any=storage.getSessionStorage("AA10_DB112_VOLUME"); //音量
  db112WireFlipList:any=storage.getSessionStorage("AA10_DB112_PHASE_FLIP"); //火零翻转
  //选择项
  LoginForm:any=storage.getSessionStorage('LoginForm');
  //本次操作sessionid
  sessionId= "";
  constructor(
    private router: Router,
    private homeService:HomeService,
    private message:NzMessageService,
    private modalService: NzModalService,
    private translateService:TranslateService) { }
  ngOnInit() {
    console.log(this.db112PhaseShiftList);
    //天线性能
    this.db112Command.forEach(item=>{
        switch(item.key){
            //同步相移
            case 'a1':
                item['min']=0;
                item['max']=3.5;
                this.sameMoveList.push(item);
                this.currentKeyVal['key'+item.key]=item.min;
                break;
            //灵敏度    
            case 'a2':
                this.currentKeyVal['key'+item.key]=this.db112PhaseShiftList[0].value;
                break;
            //火零翻转
            case 'a3':
                this.currentKeyVal['key'+item.key]=this.db112WireFlipList[0].value;
                break;
            case 'a4': //波形图
                break;
            case 'cef':  //市电频率
                break;
            case 'a5':  //读取参数
                this.readParamItem=item;
                break;
            case 'a6':
                //恢复出厂设置
                this.restoreFactoryItem=item;
                break;
            case 'a7':
                //音量
                this.currentKeyVal['key'+item.key]=this.db112VolumeList[0].value;
                break;
            default:
                break;
        }
    });
    Mysocket.oncloseWS();
    setTimeout(()=>{
      Mysocket.createSocket();
      this.initSocketMsg();
      this.chgAntType();
    },500);
  }
  ngOnDestroy(): void {
    Mysocket.oncloseWS();
  }
  exit(){
    this.close.emit(true);
  }
  //读取参数
  readParam(){
    this.chgAntType();
  }
  //恢复出厂设置
  restoreFactory(key){
      console.log(key);
    this.modalService.confirm({
      nzTitle     : this.translateService.instant('tip'),
      nzContent   : `<b>`+this.translateService.instant('eas_note_restore')+`</b>`,
      nzOkText    : this.translateService.instant('OK'),
      nzOkType    : 'primary',
      nzOnOk      : () => {
        //如果波形图运行，先停止
        if(this.state){
          this.state=false;
          this.stateChange();
        }
        this.sendAntConfigOrder(key,0);
      },
      nzCancelText: this.translateService.instant('cancel'),
      nzOnCancel  : () => {
      }
    });
  }
  //状态改变，运行或者停止
  stateChange(){
    if(this.state){
      this.chgWaveform(1);
    } else {
      this.chgWaveform(0);
    }
  }
  //波形图启/停
  chgWaveform(val){
    let data={
      LoginForm:this.LoginForm,
      DeviceMessage:{val}
    }
    this.homeService.chgWaveform(data).subscribe(res=>{
      if(res.status=1){
        this.message.success(this.translateService.instant('successfully'));
      }else {

      }
    });
  }
  //主副天线切换
  chgAntType(){
    let  data={LoginForm:this.LoginForm};
    this.homeService.chgAntType(data).subscribe(res=>{
      if(res.status=1){
        this.message.success(this.translateService.instant('successfully'));
      }else {
        this.message.error(res.message);
      }
    });
  }
  //接收信息
  initSocketMsg(){
    let _this=this;
    window.addEventListener("onmessageWS",function(e){
      let Msg=(JSON.parse(e['detail']['data']['data']));
      console.log(Msg);
      switch(Msg.moduleCode){
        // 实际同步相移
        case 'a1':
           _this.calcPosition();
           _this.currentKeyVal['key'+Msg.moduleCode]=Number(Msg.val);
           break;
        // 灵敏度
        case 'a2':
        // 火零翻转
        case 'a3':
          // 音量
        case 'a7':
            _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
            break;
          // 市电频率(50/60HZ)
        case 'cef':
          _this.currentKeyVal['key'+Msg.moduleCode]=Msg.val;
          break;
          // 波形图
        case 'a4':
            _this.xtotal=Msg.xtotal;
            _this.dealWaveMsg(Msg.val);
           _this.calcPosition();
          break;
        case 'close':
          Mysocket.oncloseWS();
          _this.offLine.emit(true);
          break;
        default:
          break;
      }
    });
  }
  dealWaveMsg(val){
    this.waveDataXList = JSON.parse(val)['x'];
    this.waveDataYList = JSON.parse(val)['y'];
    console.log(this.waveDataXList);
    console.log(this.waveDataYList);
    this.showWave();
  }
  //展示折线图
  showWave(){
    this.signalWaveOption={
      grid:{
        x:'30px',   //左侧与y轴的距离
        x2:'30px',   //右侧与y轴的距离
        y:'20px',
        y2:'20px'
      },
      color:["#FF0000","#00CC00"],
      xAxis : [
        {
          type : 'category',//类目
          data : this.waveDataXList,
          boundaryGap: true,
          axisLabel:{
            //X轴刻度配置
            interval:10,
            formatter: function(value, index) {
              return Math.round(value);
            }
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          min:0,
          max:20,
          interval:4,
        },
      ],
      series:{
        symbol: "none",
        name:'W1',
        type:'line',
        color: '#074eb1',
        data:this.waveDataYList,
        areaStyle: {
          color:'#074eb1',
        },
        splitLine:{
          show:false
        }
      }
    };
  }
  //同步相移变化时；
  sameMoveChange(){
    if(this.xtotal!==0){
      this.calcPosition();
    }
  }
  //同步相移，保存数据的变化；
  saveMove(code){
    console.log(code);
    let curVal=Number(this.currentKeyVal['key'+code]);
    console.log(curVal);
    this.sendAntConfigOrder(code,curVal);
  }
  //命令下发
  sendAntConfigOrder(code,e){
    let data={
      LoginForm:storage.getSessionStorage('LoginForm'),
      DeviceMessage:{
        moduleCode:code,
        val:e,
      }
    };
    this.homeService.order(data).subscribe(res=>{
      if(res.status==1){
        this.message.success(this.translateService.instant('eas_order_success'));
      }else {
        this.message.error(res.message);
      }
    });
  }
  //计算框的宽度
  calcPosition(){
    if(this.xtotal==0){
        return;
    }
    if($(".barItemOver")){
        $(".barItemOver").remove();
    }
    let num1=this.currentKeyVal['keycef']==50?16:14;  //第一个框的点数
    let gap1=4;//间隔 4个点
    let num2=6; //第一个框的点数
    let itemGap=this.currentKeyVal['keycef']==50?66:56;  //每组框的点数
    let wE=$(".echart2").width() -1; //总长度
    let w1=num1*wE/this.xtotal;  //第0/二/四个的长度
    let w2=num2*wE/this.xtotal; //第一/三/五个的长度
    $(".barItem0,.barItem2,.barItem4").css({'width':w1});
    $(".barItem1,.barItem3,.barItem5").css({'width':w2});
    this.calcPosition2('.barItem0',0,num1,w1,this.xtotal);
    this.calcPosition2('.barItem1',(num1+gap1),(num1+gap1+num2),w1,this.xtotal);
    this.calcPosition2('.barItem2',itemGap,itemGap+num1,w1,this.xtotal);
    this.calcPosition2('.barItem3',(itemGap+num1+gap1),(itemGap+num1+gap1+num2),w1,this.xtotal);
    this.calcPosition2('.barItem4',itemGap*2,itemGap*2+num1,w1,this.xtotal);
    this.calcPosition2('.barItem5',(itemGap*2+num1+gap1),(itemGap*2+num1+gap1+num2),w1,this.xtotal);
  }
  //计算每个框的位置
  calcPosition2(barItem,numFirst,numSecond,w1,xtotal){
    let wE=$(".echart2").width() -1; //总长度
    let xDistance=10*this.currentKeyVal['keya1'];
    console.log(xDistance);
    //第二个位置小于最大值
    if(numSecond + xDistance<=xtotal){
      $(barItem).css({left:(xDistance+numFirst)*wE/xtotal+'px'});
    } else {
      //第二个位置大于最大值，第一个位置小于最大值；
      if(numFirst+xDistance < xtotal){
        let overWid=(numSecond+xDistance-xtotal)*wE/xtotal;
        $(barItem).css({left:(xDistance+numFirst)*wE/xtotal+'px'});
        let overDiv=$("<div class='barItemOver'></div>");
        $(".echart2").append(overDiv);
        $(".barItemOver").css({'position':'absolute',top: '40px',bottom: '18px','border-bottom':'0px','width':overWid+'px',left:0,borderTopWidth:'1px',borderTopStyle:'solid',borderTopColor:$(barItem).css('border-right-color'),borderRightColor:$(barItem).css('border-right-color'),borderRightWidth:'1px',borderRightStyle:'solid'});
      } else if(numFirst+xDistance >= xtotal){
        //第一个位置大于最大值
        $(barItem).css({left:(xDistance+numFirst - xtotal)*wE/xtotal+'px'});
      }
    }
  }
}

